const Ajv = require('ajv')
const localize = require('ajv-i18n')

/**
 * 数据验证
 */
module.exports = (data, schema, alloweThrow = true, allErrors) => {
  const ajv = Ajv({ allErrors })
  const validate = ajv.compile(schema)
  const valid = validate(data)

  // 补充验证空值
  for (let i = 0; i < schema.required.length; i++) {
    let element = schema.required[i]

    if (!data[element] && data[element] !== 0) {
      const err = `${element}值不能为空`

      if (alloweThrow) {
        throw err
      }

      return err
    }
  }

  if (!valid) {
    localize.zh(validate.errors)

    const error = ajv.errorsText(validate.errors, { separator: '\n' })

    if (alloweThrow) {
      throw error
    }

    return error
  }
}
